//
//  TravelTableViewController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/27.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "TravelTableViewController.h"
#import "TravelTVCell.h"
#import "Travel.h"
#import "TravelDetailTVController.h"
#import "CycleScrollView.h"
#import "TravelHeader.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "TravelImpressionController.h"
#import "TravelDetail.h"
#import "ViewPoint.h"
#import "MJRefresh.h"


static const CGFloat MJDuration = 2.0;
/**
 * 随机数据
 */
#define MJRandomData [NSString stringWithFormat:@"随机数据---%d", arc4random_uniform(1000000)]

@interface TravelTableViewController ()

@property (nonatomic,retain) NSMutableArray *travelArr;
@property (nonatomic,retain) NSMutableData *receivedData;
@property (nonatomic,retain) UIActivityIndicatorView *activityIndicator;

// 头标题滚动视图
@property (nonatomic, retain) CycleScrollView *scrollView;
// 头标题数据数组
@property (nonatomic, retain) NSMutableArray *herderDataArray;
// 头标题视图数组
@property (nonatomic, retain) NSMutableArray *headerImageViewArray;


@end

@implementation TravelTableViewController

- (void)dealloc
{
    [_receivedData release];
    [_travelArr release];
    [_scrollView release];
    [_herderDataArray release];
    [_headerImageViewArray release];
    [_travelDetail release];
    [super dealloc];
}



- (void)MJRefresh
{
    NSLog(@"mjrefresh");
    // 1.下拉刷新
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.legendHeader beginRefreshing];
    
//    [self performSelector:@selector(headerRereshing) withObject:self.tableView.tableHeaderView afterDelay:2.0];
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
//    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    
}



#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
 
    [self loadData];
    
    // 2.模拟2秒后刷新表格UI（真实开发中，可以移除这段gcd代码）
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableView.header endRefreshing];
    });
}





//图片加载的菊花
- (void) loading{
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityIndicator.frame=CGRectMake(self.view.center.x-20, self.view.center.y-40, 30, 30);
    _activityIndicator.center=CGPointMake(self.view.center.x, self.view.center.y-30);
    _activityIndicator.color=[UIColor grayColor];
    [self.view addSubview:_activityIndicator];
    [_activityIndicator startAnimating];
}



- (void) loadData
{
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    [mgr GET:@"http://www.roadqu.com/api/mobile/qunawan/tour/featuredthemeslist&a_t=1427283397000&token=551125988bbb2&sign=52400390071b14805709425e50e76e43c8adf31b" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        //        NSLog(@"%@",responseObject);
        NSArray *data = [responseObject objectForKey:@"data"];
        //    NSLog(@"%@",data);
        self.travelArr = [NSMutableArray arrayWithCapacity:[data count]];
        
        for (NSDictionary *event in data) {
            Travel *travel = [[Travel alloc]init];
            [travel setValuesForKeysWithDictionary:event];
            
            [self.travelArr addObject:travel];
            [travel release];
        }
        [self.tableView reloadData];//相当于刷新
        
    } failure:nil];
    [self loadDataAndShow];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //    self.view.backgroundColor=[UIColor redColor];
    
    [self MJRefresh];
    
    self.navigationItem.title = @"旅游";
    
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"bg.png"] forBarMetrics:UIBarMetricsDefault];

    [self loadData];
 
    
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose o any resources that can be recreated.
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [_activityIndicator stopAnimating];
}





#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [_travelArr count];
}


/**
 *  返回每个单元格的高度
 *
 *  @param tableView <#tableView description#>
 *  @param indexPath <#indexPath description#>
 *
 *  @return <#return value description#>
 */
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Travel *travel=_travelArr[indexPath.row];
    
    static NSString *identifier = @"travel";
    TravelTVCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        cell = [[[TravelTVCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier] autorelease];
        
    }
    // Configure the cell...
    
    
    cell.travel=travel;
    
    
    return cell;
}





- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelDetailTVController *travelDetail=[[TravelDetailTVController alloc]init];
    travelDetail.travel=_travelArr[indexPath.row];
    
    
    [self.navigationController pushViewController:travelDetail animated:YES];
    
}

#pragma mark 设置header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.view.frame.size.width * .5f;
}

#pragma mark 设置header内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _scrollView;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}


- (void)loadDataAndShow
{
    self.herderDataArray = [NSMutableArray arrayWithCapacity:4];
    self.headerImageViewArray = [NSMutableArray arrayWithCapacity:4];
    
    NSURL *url = [NSURL URLWithString:@"http://www.roadqu.com/api/mobile/qunawan/tour/seasonalfunplacelist&a_t=1427507557000&token=55150e044f7c3&sign=d92c89acf2c93cd6779aced9a0c747c7684c1646"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
        NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        if (data) {
            // 存数据
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            
            NSArray *array=[dic valueForKey:@"data"];

            for (NSDictionary *dict in array) {
                TravelHeader *header = [[TravelHeader alloc]init];
                [header setValuesForKeysWithDictionary:dict];
                    UIImageView *imageView = [[[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.origin.y, self.view.frame.origin.y + 64, self.view.frame.size.width, self.view.frame.size.width * .5f)] autorelease];
                [imageView setImageWithURL:[NSURL URLWithString:header.img]];
                UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.origin.x + 40, self.view.bounds.origin.y + 80, self.view.frame.size.width - 60, 70)] autorelease];
                titleLabel.text = header.title;
                titleLabel.numberOfLines = 0;
                titleLabel.font = [UIFont boldSystemFontOfSize:14.0f];
                titleLabel.textColor = [UIColor whiteColor];
                [imageView addSubview:titleLabel];
                [self.headerImageViewArray addObject:imageView];
                [self.herderDataArray addObject:header];
                [header release];
            }
            
        } //else {
//            // 从数据库取
//        }
    
    
        
        self.scrollView = [[[CycleScrollView alloc] initWithFrame:CGRectMake(0, 64,self.view.frame.size.width, self.view.frame.size.width * .5f) animationDuration:3] autorelease];
        _scrollView.backgroundColor = [UIColor whiteColor];
        
        
        self.scrollView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex) {
            
            return _headerImageViewArray[pageIndex];
        };
        
        
        self.scrollView.totalPagesCount = ^NSInteger(void){
            return _headerImageViewArray.count;
        };
        
        //点击显示图片详情
        self.scrollView.TapActionBlock = ^(NSInteger pageIndex){
            
            NSLog(@"详情页面");
            
            // 创建详情页面
            TravelDetailTVController *detailsVC = [[TravelDetailTVController alloc] init];
//            // 取出对应页的模型
               TravelHeader *newsData = _herderDataArray[pageIndex];
            // 根据模型中的id属性重新请求数据
//            NSString *urlStr = [NSString stringWithFormat:@"http://www.roadqu.com/api/mobile/qunawan/poi/detail&a_t=1427977096000&token=55150e044f7c3&code=%@&sign=4055b4a631dc86bdfc11af79a9bc19637952a865", newsData.code];
//            // 创建URL
//            NSURL *url = [NSURL URLWithString:urlStr];
//            // 创建连接请求
//            NSURLRequest *request = [NSURLRequest requestWithURL:url];
//            // 连接
//            if ([NetworkJudgement isConnectionAvailable]) { // 如果网络可达
//                
//                [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//                    if (data) {
//                        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//                        [newsData setValuesForKeysWithDictionary:dict];
//                    }
//                    
//                }];
//                // 将模型赋值给详情页的模型属性
//                detailsVC.newsData = newsData;
//                
//            }
            
            
//            AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
//            [mgr GET:@"http://www.roadqu.com/api/mobile/qunawan/poi/detail&a_t=1427977096000&token=55150e044f7c3&code=31ae42a7d7381b5ec2d96e876c5ec1cf&sign=4055b4a631dc86bdfc11af79a9bc19637952a865" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//
//                NSDictionary *dic = [responseObject valueForKey:@"data"];
//                
//                TravelDetail *vp=[[TravelDetail alloc] init];
//                vp.code=[dic valueForKey:@"code"];
//                NSLog(@"+++++code:%@",vp.code);
//                self.travelDetail=vp;
//                [self.tableView reloadData];
//                
//            } failure:nil];

////            // 推出详情页面
            
//            detailsVC.detail=self.travelDetail;
            NSInteger num=arc4random()%4;
            detailsVC.travel=_travelArr[num];
            [self.navigationController pushViewController:detailsVC animated:YES];
            [self.view removeFromSuperview];
            
        };
//    } else {
//        // 没有网络连接...
//    }
    
}











/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
